package com.lhg.controller;

import com.lhg.model.Item;
import com.lhg.model.User;
import com.lhg.service.ItemService;
import com.lhg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.util.List;

@RestController
@RequestMapping("/tasks")
public class ItemController {
    @Autowired
    private ItemService itemService;
    @Autowired
    private UserService userService;

    @GetMapping("/mytasks")
    public ResponseEntity<?> getItemInfo(@RequestHeader("Authorization") String token) {
        try {
            User user = userService.getUserInfoByToken(token);
            List<Item> userItem = itemService.getUserItemByUid(user.getId());
            return ResponseEntity.ok(userItem);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        }
    }

    @PostMapping("/add")
    public ResponseEntity<?> addItem(@RequestHeader("Authorization") String token, @RequestBody Item item) {
        try {
            User user = userService.getUserInfoByToken(token);
            //name传过来被接收 status默认0
            item.setUid(user.getId());
            itemService.addItem(item);
            return ResponseEntity.ok("添加成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务添加失败: " + e.getMessage());
        }
    }

    @GetMapping("/{taskId}")
    public ResponseEntity<?> update(@RequestHeader("Authorization") String token,
                                    @PathVariable Integer taskId){
        try {
            User user = userService.getUserInfoByToken(token);
            Item item = itemService.getItemById(taskId);
            if(item!=null && item.getUid()==user.getId()){
                return ResponseEntity.ok(item);
            }else{
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无访问权限");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务添加失败: " + e.getMessage());
        }
    }

    @PostMapping("/save")
    public ResponseEntity<?> saveItem(@RequestBody Item item,
                                      @RequestHeader("Authorization") String token) {
        try {
            User user = userService.getUserInfoByToken(token);
            Item item1 = itemService.getItemById(item.getId());
            if(item1!=null && item1.getUid()==user.getId()){
                itemService.updateItem(item);
                return ResponseEntity.ok(item);
            }else{
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无访问权限");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务修改失败: " + e.getMessage());
        }
    }

}
